package com.jiaquyun.jcps.ui.main

import android.Manifest
import android.animation.Animator
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import com.amap.api.navi.AMapNavi
import com.amap.api.navi.AMapNaviViewOptions
import com.amap.api.navi.enums.AMapNaviViewShowMode
import com.amap.api.navi.enums.NaviType
import com.amap.api.navi.model.AMapCalcRouteResult
import com.amap.api.navi.model.NaviLatLng
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.jiaquyun.jcps.R
import com.jiaquyun.jcps.base.ViewModeAMapActivity
import com.jiaquyun.jcps.entity.OrderDetailsEntity
import com.jiaquyun.jcps.entity.OrderListEntity
import com.jiaquyun.jcps.mode.vm.RouteViewModel
import com.jiaquyun.jcps.popup.ConfirmCancelPopup
import com.jiaquyun.jcps.ui.LoadingDialog
import com.lemlin.network.HttpServiceStatus
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.activity_route2.*
import kotlinx.android.synthetic.main.include_navigation_bottom_address.*
import kotlinx.android.synthetic.main.include_navigation_bottom_details.*
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream

class Route2Activity : ViewModeAMapActivity<RouteViewModel>() {

    companion object {
        private const val EXTRA_KEY_ID = "EXTRA_KEY_ID"
        fun open(activity: Activity, orderId: Int) {
            val intent = Intent(activity, Route2Activity::class.java)
            intent.putExtra(EXTRA_KEY_ID, orderId)
            activity.startActivity(intent)
        }
    }

    private var detailsBottomSheetBehavior: BottomSheetBehavior<NestedScrollView>? = null

    private var addressBottomSheetBehavior: BottomSheetBehavior<NestedScrollView>? = null

    private var mAMapNavi: AMapNavi? = null

    private val confirmCancelPopup: ConfirmCancelPopup by lazy {
        ConfirmCancelPopup(
            context = this,
            onConfirm = { any: Any?, action: ConfirmCancelPopup.Action? ->
                confirmCancelPopup.dismiss()

                if (action == null)
                    return@ConfirmCancelPopup
                when (action) {
                    ConfirmCancelPopup.Action.CONFIRM_NAVIGATION -> {
                        //停止导航
                        mAMapNavi?.stopNavi()
                        //停止语音
                        mAMapNavi?.stopSpeak()
                        //设置预览模式
                        mAMapNaviView.setShowMode(
                            AMapNaviViewShowMode.SHOW_MODE_DISPLAY_OVERVIEW
                        )
                        //设置6秒后是否自动锁车
                        mAMapNaviView.viewOptions.apply {
                            isAutoLockCar = false
                            mAMapNaviView.viewOptions = this
                        }

                        animateInNavigationBar()
                        animateOutBottomAddress()
                        animateInBottomDetails()
                    }
                    ConfirmCancelPopup.Action.CONFIRM_CALL -> {
                        val intent = Intent(Intent.ACTION_DIAL)
                        intent.data = Uri.parse("tel:${any.toString()}")
                        startActivity(intent)
                    }
                    ConfirmCancelPopup.Action.CONFIRM_GIVE -> {
                        val rxPermissions = RxPermissions(this)
                        rxPermissions.request(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA
                        ).subscribe {
                            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                            startActivityForResult(intent, (100))
                        }
                    }
                }
            },
            onCancel = { any: Any?, action: ConfirmCancelPopup.Action? ->
                confirmCancelPopup.dismiss()
            })
    }

    override fun viewModel(): RouteViewModel {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(color = R.color.white, view = flRouteBar)
    }

    override val layoutResId: Int
        get() = R.layout.activity_route2

    override fun initView(savedInstanceState: Bundle?) {
        mAMapNavi = AMapNavi.getInstance(applicationContext)
        mAMapNavi?.addAMapNaviListener(this)
        mAMapNaviView.onCreate(savedInstanceState)
        mAMapNaviView.setAMapNaviViewListener(this)

        val options: AMapNaviViewOptions = mAMapNaviView.viewOptions
        //设置自车的图片对象
        options.carBitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_app_position)
        //设置终点位图，须在画路前设置
        options.setEndPointBitmap(BitmapFactory.decodeResource(resources, R.mipmap.ic_app_loca_1))
        //通过路线是否自动置灰
        options.isAfterRouteAutoGray = true
        //设置地图上是否显示交通路况（彩虹线）
        options.isTrafficLine = false
        //设置是否自动全览模式，即在算路成功后自动进入全览模式
        options.isAutoDisplayOverview = true
        //设置是否开启自动黑夜模式切换
        options.isAutoNaviViewNightMode = true
        //设置导航状态下屏幕是否常亮
        options.isScreenAlwaysBright = true
        //设置导航界面UI是否显示
        options.isLayoutVisible = false

//        val routeOverlayOptions = RouteOverlayOptions()
//        val drawable: Drawable = resources.getDrawable(R.drawable.bg_radius_05dp_main)
//        routeOverlayOptions.fairWayRes = ConvertUtils.drawable2Bitmap(drawable)
//        options.routeOverlayOptions = routeOverlayOptions

        mAMapNaviView.viewOptions = options

    }

    override fun initView() {

        detailsBottomSheetBehavior =
            BottomSheetBehavior.from(findViewById(R.id.nsvBottomDetailsScroll))
        addressBottomSheetBehavior =
            BottomSheetBehavior.from(findViewById(R.id.nsvBottomAddressScroll))
        animateOutBottomAddress()
        detailsBottomSheetBehavior?.addBottomSheetCallback(object :
            BottomSheetBehavior.BottomSheetCallback() {
            override fun onSlide(bottomSheet: View, slideOffset: Float) {
                if (slideOffset > 0.5f) {
                    ivBottomDetailsDirection.setImageResource(R.mipmap.ic_app_down)
                } else {
                    ivBottomDetailsDirection.setImageResource(R.mipmap.ic_app_top)
                }
            }

            override fun onStateChanged(bottomSheet: View, newState: Int) = Unit
        })

        ivRouteBack.setOnClickListener {
            this.onBackPressed()
        }
        tvRouteNavigation.setOnClickListener {
            mAMapNavi?.startNavi(NaviType.GPS)
        }

        llBottomDetailsContactClient.setOnClickListener {
            viewModel.orderDetailsDataLiveData.value?.httpData?.data?.let {
                confirmCancelPopup.setMessage("联系电话：${it.mobile}")
                    .setAction(ConfirmCancelPopup.Action.CONFIRM_CALL)
                    .setAny(it.mobile)
                    .showPopupWindow()
            }
        }

        ivBottomAddressContactClient.setOnClickListener {
            viewModel.orderDetailsDataLiveData.value?.httpData?.data?.let {
                confirmCancelPopup.setMessage("联系电话：${it.mobile}")
                    .setAction(ConfirmCancelPopup.Action.CONFIRM_CALL)
                    .setAny(it.mobile)
                    .showPopupWindow()
            }
        }

        tvBottomDetailsConfirmService.setOnClickListener {
            viewModel.orderDetailsDataLiveData.value?.httpData?.data?.let {
                confirmCancelPopup.setMessage("确认已经送达客户手中或指定配送地点？")
                    .setAction(ConfirmCancelPopup.Action.CONFIRM_GIVE)
                    .setAny(it.id)
                    .showPopupWindow()
            }
        }
    }

    override fun initData() {
        intent?.getIntExtra(EXTRA_KEY_ID, (0))?.let {
            if (it == 0)
                return@let
            viewModel.orderDetails(it.toString())
        }
    }

    override fun initViewMode() {
        viewModel.orderDetailsDataLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                response.httpData?.data?.let {
                    fillData(it)
                }
            }
        })

        viewModel.baseServiceLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                confirmCancelPopup.setMessage("辛苦了，已经成功送达")
                    .setAction(null)
                    .setAny(null)
                    .showPopupWindow()
            }
        })

        viewModel.photoLiveData.observe(this, Observer { response ->

            if (response.statusCode == HttpServiceStatus.Status.START) {
                LoadingDialog.show(this)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                LoadingDialog.dismiss()
                response.httpData?.data?.let {
                    viewModel.orderDetailsDataLiveData.value?.httpData?.data?.let { details ->
                        viewModel.orderService(details.id.toString(), it.url)
                    }
                }
            }
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                LoadingDialog.dismiss()
                toast(response.statusTip)
            }
        })
    }

    private fun fillData(orderDetails: OrderDetailsEntity) {
        mAMapNavi?.calculateRideRoute(
            NaviLatLng(
                orderDetails.end_lat.toDouble(),
                orderDetails.end_lng.toDouble()
            )
        )

        val distance: StringBuilder = StringBuilder().append(orderDetails.distance).append("m")

        tvRouteDistance.text = StringBuilder().append(orderDetails.distance).append("m")
        tvBottomDetailsPayType.text =
            if (orderDetails.pay_name.isNullOrEmpty()) "在线支付" else orderDetails.pay_name
        tvBottomDetailsPrice.text = StringBuilder().append("￥").append(orderDetails.price)
        tvBottomDetailsAddressStart.text = orderDetails.start_address
        tvBottomDetailsAddressEnd.text = orderDetails.end_address
        tvBottomDetailsDistance.text = distance
        tvBottomDetailsAmount.text =
            StringBuilder().append("在线支付").append(orderDetails.order_amount).append("元")
        tvBottomDetailsTime.text =
            StringBuilder().append("顾客下单时间")
                .append(TimeUtils.millis2String((orderDetails.createtime * 1000), ("HH:mm")))
        tvBottomDetailsUserNote.text = orderDetails.user_note

        tvBottomAddressPosition.text = "#${orderDetails.order_no}"
        tvBottomAddressDistance.text = distance
        tvBottomAddressStart.text = orderDetails.start_address
        tvBottomAddressEnd.text = orderDetails.end_address
    }

    override fun onResume() {
        super.onResume()
        mAMapNaviView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mAMapNaviView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mAMapNaviView.onDestroy()
        mAMapNavi?.stopNavi()
        mAMapNavi?.destroy()
    }

    override fun onBackPressed() {
        if (mAMapNavi?.naviType == NaviType.GPS) {
            confirmCancelPopup.setMessage("正在导航，是否退出？")
                .setAction(ConfirmCancelPopup.Action.CONFIRM_NAVIGATION)
                .setAny(null)
                .showPopupWindow()
        } else {
            super.onBackPressed()
        }
    }


    //导航初始化成功时的回调函数
    override fun onInitNaviSuccess() {
        mAMapNavi?.setUseInnerVoice(true, true)
        mAMapNavi?.startGPS()
    }

    //导航初始化失败回调
    override fun onInitNaviFailure() {
        toast("导航初始化失败")
    }

    //路线规划成功回调
    override fun onCalculateRouteSuccess(p0: AMapCalcRouteResult?) {
    }

    //路线规划失败回调
    override fun onCalculateRouteFailure(p0: AMapCalcRouteResult?) {
        toast("路线规划失败:${p0?.errorDescription}")
    }

    //启动导航后的回调函数
    override fun onStartNavi(p0: Int) {
        //锁车态
        mAMapNaviView.setShowMode(AMapNaviViewShowMode.SHOW_MODE_LOCK_CAR)
        mAMapNaviView.viewOptions.apply {
            //设置6秒后是否自动锁车
            isAutoLockCar = true
            mAMapNaviView.viewOptions = this
        }
        animateOutNavigationBar()
        animateOutBottomDetails()
        animateInBottomAddress()
    }

    //到达目的地后回调函数
    override fun onArriveDestination() {
        mAMapNaviView.setShowMode(AMapNaviViewShowMode.SHOW_MODE_DISPLAY_OVERVIEW)
        mAMapNavi?.startNavi(NaviType.NONE)
        animateInBottomDetails()
        animateOutBottomAddress()
        toast("到达目的地")
    }

    //导航视图展示模式变化回调
    override fun onNaviViewShowMode(p0: Int) {
        //p0 == 1-锁车态 2-全览态 3-普通态

    }

    //导航条移除屏幕动画
    private fun animateOutNavigationBar() {
        llRouteNavigation.animate().translationY(-llRouteNavigation.height.toFloat())
            .setInterpolator(LinearInterpolator())
            .setListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(animation: Animator?) = Unit
                override fun onAnimationCancel(animation: Animator?) = Unit
                override fun onAnimationStart(animation: Animator?) = Unit
                override fun onAnimationEnd(animation: Animator?) {
                    llRouteNavigation.visibility = View.GONE
                }
            }).start()
    }

    //导航条移入屏幕动画
    private fun animateInNavigationBar() {
        llRouteNavigation.visibility = View.VISIBLE
        llRouteNavigation.animate().translationY(0f).setInterpolator(LinearInterpolator())
            .withLayer()
            .setListener(null).start()
    }

    //底部详情移除屏幕
    private fun animateOutBottomDetails() {
        detailsBottomSheetBehavior?.setPeekHeight((0), (true))
        detailsBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
    }

    //底部详情移入屏幕
    private fun animateInBottomDetails() {
        detailsBottomSheetBehavior?.setPeekHeight(ConvertUtils.dp2px((75f)), (true))
        detailsBottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
    }

    //底部地址移除屏幕
    private fun animateOutBottomAddress() {
        addressBottomSheetBehavior?.setPeekHeight((0), (true))
        addressBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
    }

    //底部地址移入屏幕
    private fun animateInBottomAddress() {
        val spec: Int = View.MeasureSpec.makeMeasureSpec(
            (0), View.MeasureSpec.UNSPECIFIED
        )
        val height: Int = nsvBottomAddressScroll.apply {
            measure(spec, spec)
        }.measuredHeight
        addressBottomSheetBehavior?.setPeekHeight(height, (true))
        addressBottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
    }


    private var photoFile: File? = null

    //相机点击事件:打开照相机（该方式获取到的图片是原图）
    private fun openPhoto() {
        val localPath: String = applicationContext.filesDir.absolutePath + "/jiaquyun"
        val dir = File(localPath)
        if (!dir.exists())
            dir.mkdirs()
        photoFile = File(("${dir.path}/${System.currentTimeMillis()}.png"))
        photoFile?.let {
            if (!it.exists())
                it.createNewFile()
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            intent.putExtra(
                MediaStore.EXTRA_OUTPUT,
                getUriForFile(this, it)
            )
            startActivityForResult(intent, (100))
        }
    }

    private fun getUriForFile(context: Context, file: File): Uri =
        if (Build.VERSION.SDK_INT >= 24) {
            FileProvider.getUriForFile(
                context, ("${context.packageName}.fileprovider"), file
            )
        } else Uri.fromFile(file)


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        if (resultCode == RESULT_OK && requestCode == 100) photoFile?.let {
//            viewModel.uploadImage(it.path)
//        }
        if (resultCode == RESULT_OK && requestCode == 100) {
            try {
                val bitmap: Bitmap? = data?.extras?.get("data") as? Bitmap
//                val path: String = Environment.getExternalStorageDirectory().toString()
                val path: String = applicationContext.filesDir.absolutePath
                var outStream: OutputStream? = null
                val file = File(path, "${System.currentTimeMillis()}.png")
                outStream = FileOutputStream(file)
                bitmap?.compress(Bitmap.CompressFormat.PNG, 100, outStream)
                outStream.close()
                viewModel.uploadImage(file.path)
            } catch (e: Exception) {
                toast("图像保存失败！${e.message}")
            }
        }
    }
}